package com.ccl.iot.asynctask;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;

import com.ccl.iot.device.IOTSubBLir;
import com.ccl.iot.dialogs.StudyIrDialog;
import com.ccl.iot.ir.BlirConst;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.views.SubBlirControlView;

import cn.com.broadlink.sdk.BLLet;
import cn.com.broadlink.sdk.constants.BLAppSdkErrCode;
import cn.com.broadlink.sdk.constants.controller.BLDeviceState;
import cn.com.broadlink.sdk.param.controller.BLStdControlParam;
import cn.com.broadlink.sdk.result.controller.BLStdControlResult;

//学习红外
public class StudyIrTask extends AsyncTask<String, Integer, BLStdControlResult> {

    private IOTSubBLir mSubBLir;
    private boolean mQueryIr;
    private int mQueryTime = 0;
    private String mKeyType;
    private String mKeyName;

    private View mOfflineMask;
    private SubBlirControlView.OnDevOnlineChangeListener mOnlineChangeListener;
    protected StudyIrDialog progressDialog;
    protected Context mContext;

    public StudyIrTask(Context context, IOTSubBLir subBLir, SubBlirControlView.OnDevOnlineChangeListener l, View mask) {
        mContext = context;
        mSubBLir = subBLir;
        mOnlineChangeListener = l;
        mOfflineMask = mask;

        progressDialog = new StudyIrDialog(mContext);
        progressDialog.show();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                mQueryIr = false;
            }
        });
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        progressDialog.setProgress(values[0]);
    }

    @Override
    protected BLStdControlResult doInBackground(String... params) {
        mKeyType = params[0];
        mKeyName = params[1];
        /**发送 RM 进入学习命令**/
        BLStdControlParam intoStudyParam = new BLStdControlParam();
        intoStudyParam.setAct(BlirConst.ACT_SET);
        intoStudyParam.getParams().add("irdastudy");
        BLStdControlResult intoStudyResult = BLLet.Controller.dnaControl(mSubBLir.getDid(), null, intoStudyParam);
        //判断是否进入学习成功
        if (intoStudyResult != null && intoStudyResult.getStatus() == BLAppSdkErrCode.SUCCESS) {
            mQueryIr = true;
            BLStdControlResult queryRtudyResult = null;
            while (mQueryIr) {
                //隔间500ms 查询一次，是否学习成功
                SystemClock.sleep(500);

                mQueryTime += 500;
                publishProgress(mQueryTime);

                //超过60s超时，则不再继续查询
                if (mQueryTime > 60 * 1000) {
                    mQueryIr = false;
                }

                /**进入学习成功之后，等待RM学习，查询RM是否学习到红外**/
                BLStdControlParam queryIrStudyParam = new BLStdControlParam();
                queryIrStudyParam.setAct(BlirConst.ACT_GET);
                queryIrStudyParam.getParams().add("irda");
                queryRtudyResult = BLLet.Controller.dnaControl(mSubBLir.getDid(), null, queryIrStudyParam);
                if (queryRtudyResult != null) {
                    Log.e("SendIr", "study State: " + queryRtudyResult.getStatus() + ", Msg: " + queryRtudyResult.getMsg());
                    if (queryRtudyResult.getStatus() == BLAppSdkErrCode.SUCCESS) {
                        mQueryIr = false;
                        return queryRtudyResult;
                    }/* else {
                            int state = BLLet.Controller.queryDeviceState(mSubBLir.getDid());
                            if (state == 3) {
                                queryRtudyResult.setStatus(state);
                                break;
                            }
                        }*/
                }
            }

            if (queryRtudyResult == null) {
                queryRtudyResult = new BLStdControlResult();
            }
            int state = BLLet.Controller.queryDeviceState(mSubBLir.getDid());
            if (state == 3) {
                queryRtudyResult.setStatus(state);
            }else{
                queryRtudyResult.setStatus(-1);
            }

            return queryRtudyResult;

        } else {
            BLStdControlResult queryRtudyResult = new BLStdControlResult();
            int state = BLLet.Controller.queryDeviceState(mSubBLir.getDid());
            if (state == 3) {
                queryRtudyResult.setStatus(state);
            } else {
                queryRtudyResult.setStatus(-1);
            }
            return queryRtudyResult;
        }

    }

    @Override
    protected void onPostExecute(BLStdControlResult stdControlResult) {
        super.onPostExecute(stdControlResult);
        progressDialog.dismiss();
        if (stdControlResult != null && stdControlResult.getStatus() == BLAppSdkErrCode.SUCCESS) {

            try {
                String irCodeStr = (String) stdControlResult.getData().getVals().get(0).get(0).getVal();
                //                    mIrCodeView.setText(irCodeStr);
                Messager.Show("学习红外码成功 ");
                Log.e("AddCodeV2", "mKeyType: "+mKeyType+", mKeyName: "+mKeyName+", irCodeStr: "+irCodeStr);
                new SaveIrTask(mContext, mSubBLir).execute(mKeyType, mKeyName, irCodeStr);
            } catch (Exception e) {
                Messager.Show("学习红外码失败");
            }
        } else if (stdControlResult != null && stdControlResult.getStatus() == BLDeviceState.OFFLINE) {
            Messager.Show("设备已经离线");
            mSubBLir.setRealOnline(false);
            if (mOnlineChangeListener != null) {
                mOnlineChangeListener.onDevOnlineChange();
            } else {
                mOfflineMask.setVisibility(View.VISIBLE);
            }
        } else {
            Messager.Show("学习红外码失败...");
        }
    }
}